package com.example.springmvc.config;

import com.example.springmvc.common.JwtCodec;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

/**
 * @author fanhang
 */
@Configuration
public class JwtInterceptor implements WebRequestInterceptor {
    private static final String AUTH_HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";
    private final JwtCodec jwtCodec;

    public JwtInterceptor(JwtCodec jwtCodec) {
        this.jwtCodec = jwtCodec;
    }

    @Override
    public void preHandle(WebRequest request) throws Exception {
        String auth = request.getHeader(AUTH_HEADER);
        if (auth == null || auth.isBlank()) {
            return;
        }
        if (auth.startsWith(TOKEN_PREFIX)) {
            String token = auth.substring(7);
            Long userId = jwtCodec.decode(token.trim());
            request.setAttribute(SessionUser.SESSION_ATTR_NAME, userId, RequestAttributes.SCOPE_REQUEST);
        }
    }

    @Override
    public void postHandle(WebRequest request, ModelMap model) throws Exception {
    }

    @Override
    public void afterCompletion(WebRequest request, Exception ex) throws Exception {
    }
}
